//
//  DWMessageManger.m
//  LGMessageAccept
//
//  Created by dangwc on 2019/9/5.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "DWMessageManger.h"


@interface DWMessageManger()
@property (nonatomic,strong) NSThread *thread;
@end

@implementation DWMessageManger
+(instancetype)shareManager{
    static DWMessageManger *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DWMessageManger alloc] init];
        manager.pollInterval = 10;//默认轮询时间
    });
    return manager;
}

-(NSThread *)thread{
    if (!_thread) {
        _thread = [[NSThread alloc] initWithTarget:self selector:@selector(msgBackgroundThread) object:nil];
        _thread.name = @"massageThread";
    }
    return _thread;
}

-(void)msgBackgroundThread{
    @autoreleasepool {
        NSThread *currentThread = [NSThread currentThread];
        BOOL isCancel = [currentThread isCancelled];
        NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
        //开启runloop
        [currentRunLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        while (!isCancel && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
            isCancel = [currentThread isCancelled];
        }
    }
}


-(void)startPolling{
    
    if (self.timer) {
        dispatch_resume(self.timer);
    }
    
    if (![self.thread isExecuting]) {
        [self.thread start];
        __weak typeof(self) weakSelf = self;
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        //开始时间
        dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC);
        //间隔时间
        uint64_t interval = weakSelf.pollInterval * NSEC_PER_SEC;
        dispatch_source_set_timer(self.timer, start, interval, 0);
        //设置回调
        dispatch_source_set_event_handler(self.timer, ^{
            [weakSelf beginRequest];
        });
        //启动timer
        dispatch_resume(self.timer);
    }
}

-(void)beginRequest{
    // 异步请求
    [self performSelector:@selector(updataMeassgeCount) onThread:self.thread withObject:nil waitUntilDone:NO];
}

-(void)closeThread{
    //告诉后台该线程进入休眠状态
    NSLog(@"message线程进入休眠状态");
}

-(void)stopThread{
    [self.thread cancel];
    [self performSelector:@selector(closeThread) onThread:self.thread withObject:nil waitUntilDone:NO];
}

-(void)updataMeassgeCount{
    [DWMessageRequest lg_MessageCountBaseUrl:self.subUrl userID:self.userID Callback:^(BOOL isUpdate) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:DWREFRESHMESSAGEDATA object:@{@"MsgUpdate":[NSNumber numberWithBool:isUpdate]}];
        });
    }];


}


-(void)stopPolling{
    if (self.timer) {
      dispatch_suspend(self.timer);
    }
}

@end
